<template>
	<div class="container-outer">
		<!-- 通过树形空间增加组织架构显示 -->
		<div class="organization">
			<a-tree v-model:expandedKeys="expandedKeys" :field-names="{ title: 'name', key: 'id' }" :load-data="onLoadData" :tree-data="treeData" @select="selectNode" />
		</div>

		<div class="right">
			<div class="toolbar mt-2">
				<a-form ref="searchRef" :model="searchState" :label-col="{ style: { width: '80px' } }" @finish="current = 1; initData()">
					<a-row :gutter="20">
						<template v-if="searchExpand">
							<a-col :span="4">
								<a-form-item label="姓名">
									<a-input v-model:value="searchState['fullname']" placeholder="请输入" allow-clear></a-input>
								</a-form-item>
							</a-col>
							<a-col :span="4">
								<a-form-item label="用户名" class="mb-0">
									<a-input v-model:value="searchState['username']" placeholder="请输入" allow-clear></a-input>
								</a-form-item>
							</a-col>
							<a-col :span="4">
								<a-form-item label="手机号" class="mb-0">
									<a-input v-model:value="searchState['mobile']" placeholder="请输入" allow-clear></a-input>
								</a-form-item>
							</a-col>
							<!--							<a-col :span="8">-->
							<!--								<a-form-item label="手机号码">-->
							<!--									<a-input v-model:value="searchState['mobile']" placeholder="请输入" allow-clear></a-input>-->
							<!--								</a-form-item>-->
							<!--							</a-col>-->
							<!--							<a-col :span="8">-->
							<!--								<a-form-item label="用户状态">-->
							<!--									<a-select v-model:value="searchState.status" placeholder="请选择" allow-clear>-->
							<!--										<a-select-option :value="1">正常</a-select-option>-->
							<!--										<a-select-option :value="0">冻结</a-select-option>-->
							<!--									</a-select>-->
							<!--								</a-form-item>-->
							<!--							</a-col>-->
							<!--							<a-col :span="8">-->
							<!--								<a-form-item label="性别" class="mb-0">-->
							<!--									<a-select v-model:value="searchState.gender" placeholder="请选择" allow-clear>-->
							<!--										<a-select-option :value="1">男</a-select-option>-->
							<!--										<a-select-option :value="2">女</a-select-option>-->
							<!--									</a-select>-->
							<!--								</a-form-item>-->
							<!--							</a-col>-->
							<!--
						<a-col :span="8">
							<a-form-item label="公司">
								<a-input v-model:value="searchState.company" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
							-->
							<a-col :span="4">
								<a-form-item label="项目名称">
									<a-input v-model:value="searchState.department" placeholder="请输入" allow-clear></a-input>
								</a-form-item>
							</a-col>
						</template>

						<a-col :span="16">
							<a-space style="margin-left:80px">
								<a-button type="primary" html-type="submit">
									<search-outlined />搜索
								</a-button>

								<!--
							<a @click="searchExpand = !searchExpand">
								<template v-if="searchExpand">
									<a-space>
										<up-outlined />
										<span>收起</span>
									</a-space>
								</template>
								<template v-else>
									<a-space>
										<down-outlined />
										<span>展开</span>
									</a-space>
								</template>
							</a>
								-->
								<a-button v-permission="179" type="primary" @click="addUser">
									<plus-outlined />添加用户
								</a-button>
								<a-button v-permission="182" danger :disabled="!selectedRowKeys.length" @click="deleteUser">
									<delete-outlined />删除用户
								</a-button>

								<a-upload v-permission="183" name="upload" :show-upload-list="false" :action="`${baseURL}/user/import`" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="() => uploading = true" @change="uploading = false; initData()">
									<a-button>
										<template v-if="uploading">
											<loading-outlined />导入中...
										</template>
										<template v-else>
											<import-outlined />导入用户
										</template>
									</a-button>
								</a-upload>
								<a-button v-permission="183" type="link" @click="downloadUserTpl">
									<download-outlined />下载用户模板
								</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="container mt-2">
				<!--				<div class="mb-2">-->
				<!--					<a-space>-->
				<!--						<a-button v-permission="179" type="primary" @click="addUser">-->
				<!--							<plus-outlined />添加用户-->
				<!--						</a-button>-->
				<!--						<a-button v-permission="182" danger :disabled="!selectedRowKeys.length" @click="deleteUser">-->
				<!--							<delete-outlined />删除用户-->
				<!--						</a-button>-->

				<!--						<a-upload v-permission="183" name="upload" :show-upload-list="false" :action="`${baseURL}/user/import`" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="() => uploading = true" @change="uploading = false; initData()">-->
				<!--							<a-button>-->
				<!--								<template v-if="uploading">-->
				<!--									<loading-outlined />导入中...-->
				<!--								</template>-->
				<!--								<template v-else>-->
				<!--									<import-outlined />导入用户-->
				<!--								</template>-->
				<!--							</a-button>-->
				<!--						</a-upload>-->
				<!--						<a-button v-permission="183" type="link" @click="downloadUserTpl">-->
				<!--							<download-outlined />下载用户模板-->
				<!--						</a-button>-->
				<!--					</a-space>-->
				<!--				</div>-->

				<a-table row-key="id" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: changeSelectedRowKeys }" :scroll="tableScroll" :data-source="userSource" :pagination="pagination" :loading="loading" :columns="columns" @change="initData">
					<template #bodyCell="{ column, record }">
						<a-image v-if="column.key === 'head_img_url'" :src="record.head_img_url" :width="60" />

						<template v-else-if="column.key === 'company'">
							<a-space>
								<a-tag v-for="( item ) in Array.from(new Set(record.departments.map((d) => d.company?.name))) " :key="item">{{ item }}</a-tag>
							</a-space>
						</template>

						<template v-else-if="column.key === 'departments'">
							<a-tooltip :title="record.departments.map(item => item.name).join(',')">
								<a-tag v-for="( item ) in record.departments " :key="item.id">{{ item.name }}</a-tag>
							</a-tooltip>
						</template>

						<template v-else-if="column.key === 'privilege'">
							<a-button size="small" @click="userId = record.id; initUserRole()">设置</a-button>
						</template>
						<template v-if="column.dataIndex === 'manually_signed_file_path'">
							<span v-if="record['manually_signed_file_path']">
								<a-image :width="60" :height="60" :src="record['manually_signed_file_path'][0].url || record['manually_signed_file_path']" />
							</span>
							<!--                <span style="text-align: right" class="flex-auto">-->
							<!--								<a-button size="small" @click="editManuallySignedPic(record)">{{ record['manually_signed_file_path']? '修改': '签名' }}</a-button>-->
							<!--							</span>-->
						</template>
						<template v-else-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="180" type="link" @click="showUser(record)">
									<!--									<right-outlined />查看-->
									<a-tooltip placement="top">
										<template #title>
											<span>查看</span>
										</template>
										<svg-icon name="look" class="svg-icon" />
									</a-tooltip>
								</a-button>
								<a-button v-permission="181" type="link" @click="editUser(record)">
									<!--									<edit-outlined />修改-->
									<a-tooltip placement="top">
										<template #title>
											<span>修改</span>
										</template>
										<svg-icon name="update" class="svg-icon" />
									</a-tooltip>
								</a-button>
								<a-button v-permission="181" type="link" @click="editManuallySignedPic(record)">
									<!--									<edit-outlined />签名-->
									<a-tooltip placement="top">
										<template #title>
											<span>签名</span>
										</template>
										<svg-icon name="signature" class="svg-icon" />
									</a-tooltip>
								</a-button>
								<a-button v-permission="182" type="link" style="color:#ff7875" @click="deleteUser(record.id)">
									<!--									<delete-outlined />删除-->
									<a-tooltip placement="top">
										<template #title>
											<span>删除</span>
										</template>
										<svg-icon name="delete" class="svg-icon" />
									</a-tooltip>
								</a-button>
							</a-space>
						</template>
					</template>
				</a-table>
			</div>
			<a-modal v-model:visible="visible" width="1000px" title="创建用户" @ok="saveUser">
				<a-form ref="formRef" :model="formState" :rules="formRules" v-bind="{ labelCol: { style: { width: '100px' } } }">
					<table cellspacing="0" cellpadding="0" width="100%">
						<tr>
							<td colspan="2">
								<a-form-item label="姓名" name="fullname">
									<a-input v-model:value="formState.fullname" />
								</a-form-item>
							</td>
							<td>
								<a-form-item label="手机号" name="mobile">
									<a-input v-model:value="formState.mobile" placeholder="可用于账号登录" />
								</a-form-item>
							</td>
						</tr>
						<tr>
							<td>
								<a-form-item label="账号" name="username">
									<a-input v-model:value="formState.username" />
								</a-form-item>
							</td>
							<td>
								<a-form-item label="密码" name="password">
									<a-input-password v-model:value="formState.password" autocomplete="off" />
								</a-form-item>
							</td>
							<td>
								<a-form-item label="重复密码" name="confirm_password">
									<a-input-password v-model:value="formState.confirm_password" autocomplete="off" />
								</a-form-item>
							</td>
						</tr>
						<tr>
							<td colspan="2">
								<a-form-item label="所属部门" name="department_ids">
									<a-tree-select v-model:value="formState.department_ids" :show-search="true" :tree-checkable="false" multiple :dropdown-style="{}" tree-default-expand-all :tree-data="departmentSource" :field-names="{ children: 'children', label: 'label', value: 'value' }" tree-node-filter-prop="label"></a-tree-select>
								</a-form-item>
							</td>
							<td>
								<a-form-item label="职务" name="position">
									<a-input v-model:value="formState.position" />
								</a-form-item>
							</td>
						</tr>
						<tr>
							<!--
						<td>
							<a-form-item label="角色" name="role_id">
								<a-select v-model:value="formState.role_id">
									<a-select-option v-for="(item) in roleOptions" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
								</a-select>
							</a-form-item>
						</td>
							-->
							<td>
								<a-form-item label="邮箱" name="email">
									<a-input v-model:value="formState.email" />
								</a-form-item>
							</td>
							<td>
								<a-form-item label="性别" name="gender">
									<a-radio-group v-model:value="formState.gender">
										<a-radio :value="1">男</a-radio>
										<a-radio :value="2">女</a-radio>
									</a-radio-group>
								</a-form-item>
							</td>
							<td>
								<a-form-item label="账户状态" name="status">
									<a-radio-group v-model:value="formState.status">
										<a-radio :value="1">正常</a-radio>
										<a-radio :value="0">冻结</a-radio>
									</a-radio-group>
								</a-form-item>
							</td>
						</tr>
					</table>
				</a-form>
			</a-modal>
			<div>
				<a-modal v-model:visible="show" width="1000px" title="查看用户信息" @ok="handleOk">
					<p>
						<label>机号:</label>
						{{ showData.mobile }}
					</p>
					<p>
						<label>用户账号:</label>
						{{ showData.username }}
					</p>
					<p>
						<label>姓名:</label>
						{{ showData.fullname }}
					</p>
					<p>
						<label>工号:</label>
						{{ showData.employee_no }}
					</p>
					<p>
						<label>角色:</label>
						{{ showData.role_lable }}
					</p>
					<p>
						<label>所属部门:</label>
						{{ showData.department_lable }}
					</p>
					<p>
						<label>职务:</label>
						{{ showData.position }}
					</p>
				</a-modal>
			</div>

			<a-modal v-model:visible="roleTableVisible" width="1000px" title="角色管理">
				<a-table row-key="id" :data-source="userRoleSource" :pagination="false" :columns="roleColumns">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button type="link" @click="editUserRole(record)">
									<edit-outlined />修改
								</a-button>
								<a-popconfirm title="确定要删除当前角色吗？" ok-text="是" cancel-text="否" @confirm="deleteRole(record.id)">
									<a-button type="link" style="color:#ff7875">
										<delete-outlined />删除
									</a-button>
								</a-popconfirm>
							</a-space>
						</template>
					</template>
				</a-table>

				<template #footer>
					<a-button key="back" type="primary" @click="addUserRole">新增</a-button>
					<a-button key="submit" type="primary" :loading="loading" @click="roleTableVisible = false">关闭</a-button>
				</template>
			</a-modal>

			<a-modal v-model:visible="roleDialogVisible" width="600px" title="角色信息" @ok="saveUserRole">
				<a-form ref="roleFormRef" :model="roleFormState" :rules="roleFormRules" v-bind="{ labelCol: { style: { width: '100px' } } }">
					<a-form-item label="部门" name="department_id">
						<a-tree-select v-model:value="roleFormState.department_id" :show-search="true" :tree-checkable="false" :tree-data="departmentSource" :field-names="{ children: 'children', label: 'label', value: 'value' }" tree-node-filter-prop="label"></a-tree-select>
					</a-form-item>

					<a-form-item label="角色" name="role_id">
						<a-select v-model:value="roleFormState.role_id" :options="roleSource" :field-names="{ label: 'name', value: 'id' }"></a-select>
					</a-form-item>
				</a-form>
			</a-modal>
			<a-modal v-model:visible="manuallySignedVisible" width="600px" title="签名照片" @ok="saveUserManuallySigned">
				<a-form ref="manuallySigned" :model="manuallySignedFormState" v-bind="{ labelCol: { style: { width: '100px' } } }">
					<a-form-item label="签名照片" name="file_path" :rules="{ required: true, message: '请上传签名照片' }">
						<a-upload v-model:file-list="manuallySignedFormState.file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeClientUpload" @change="changeClientUpload">
							<a-button>
								<template v-if="manuallySignedFormState.uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传照片
								</template>
							</a-button>
						</a-upload>
						<span style="color:#ccc">
							提交签名照片
							<span style="color:red">JPG,PNG</span>文件, 尺寸不能超过
							<span style="color:red">135*60px</span>
						</span>
					</a-form-item>
				</a-form>
			</a-modal>
		</div>
	</div>
</template>
<script setup lang="jsx">
import dayjs from 'dayjs';

import { SearchOutlined, EditOutlined, RightOutlined, DeleteOutlined, ImportOutlined, PlusOutlined, DownloadOutlined, LoadingOutlined } from "@ant-design/icons-vue";

import { reactive, ref, computed, getCurrentInstance } from "vue";

const { proxy } = getCurrentInstance();

import { post, treeToList } from "../utils";
import { usePagination } from "vue-request";

//import { Upload } from '../components';

import { baseURL } from '../utils/request';

//11/15 11:23 没雨溪:增加组织结构树形选择

const treeData = ref([]);

const expandedKeys = ref([]);

const initTreeData = () => {
	post("company/tree").then(data => {
		treeData.value = data;
		//默认展开所有
		expandedKeys.value = treeToList(JSON.parse(JSON.stringify(data)), [])
			.filter(d => !d.parent_id && d.parent_id !== 0)
			.map(d => d?.id);
		// console.log('-----', expandedKeys.value)
	});

};
initTreeData();

//选中树节点
const departmentNode = ref({});

const selectNode = (selectedKeys, info) => {
	departmentNode.value = info.node;
	/*
	post('user', { department_id: info.node.id })
		.then(res => {
			userSource.value = res.data
		})
	*/

	initData();
	// post('user', { ids: [selectedKeys] })
	// 	.then(res => {
	// 		console.log(res.data)
	// 		userSource.value = res.data
	// 	})
	// userSource.value = newData;
};

const searchRef = ref();
const searchState = reactive({});
const searchExpand = ref(true);

const statusOptions = [
	{
		value: 1,
		label: "正常"
	},
	{
		value: 0,
		label: "冻结"
	}
];
const genderOptions = [
	{
		value: 1,
		label: "男"
	},
	{
		value: 2,
		label: "女"
	}
];
const roleOptions = [
	{
		value: 1,
		label: "超级管理员"
	},
	{
		value: 2,
		label: "分公司管理员"
	},
	{
		value: 3,
		label: "项目部/公司部门管理员"
	},
	{
		value: 4,
		label: "项目部部门管理员"
	},
	{
		value: 5,
		label: "员工"
	},
	{
		value: 6,
		label: "供应商"
	},
]

const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 250 }));

const columns = [
	// {
	// 	title: "ID",
	// 	dataIndex: "id",
	// 	key: "id",
	// 	width: 60,
	// 	align: 'center',
	// 	fixed: "left"
	// },
	{
		title: "用户名",
		dataIndex: "username",
		sorter: false,
		fixed: "left",
		width: 100,
		align: 'center',
		ellipsis: true,
		customRender: ({ text }) => {
			return (
				<a-tooltip placement="topLeft" title={text}>
					{text}
				</a-tooltip>
			)
		}
	},
	{
		title: "姓名",
		dataIndex: "fullname",
		sorter: false,
		width: 80,
		align: 'center',
		customRender: ({ text, record }) => {
			return (
				<span>
					<a-badge status={record.status === 1 ? 'success' : 'error'}/>
					<a-tooltip placement="topLeft" title={text}>
						{text}
					</a-tooltip>
				</span>
			)
		}
	},
	// {
	// 	title: "状态",
	// 	sorter: false,
	// 	width: 50,
	// 	align: "center",
	// 	dataIndex: "status",
	// 	customRender: ({ text, record, index, column }) => {
	// 		//未设置dataIndex，text和record返回值相同
	// 		return <a-tag color={text === 1 ? 'green' : 'red'}>{statusOptions.find(d => d.value === text)?.label}</a-tag>;
	// 	}
	// },
	/*
	{
		title: "头像",
		key: "head_img_url",
		sorter: false,
		width: 140,
		align: "center"
	},
	*/
	{
		title: "性别",
		dataIndex: "gender",
		sorter: false,
		width: 50,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return <a-tag color="blue">{genderOptions.find(d => d.value === text)?.label}</a-tag>
		}
	},
	/*
	{
		title: "生日",
		dataIndex: "birthday",
		sorter: false,
		align: 'center',
		width: 120
	},
	*/
	{
		title: "手机号",
		dataIndex: "mobile",
		sorter: false,
		width: 100,
		align: "center"
	},
	/*
	{
		title: "座机号",
		dataIndex: "phone",
		sorter: false,
		width: 140
	},
	{
		title: "邮箱",
		dataIndex: "email",
		sorter: false,
		width: 160,
		ellipsis: true
	},
	{
		title: "公司",
		key: "company",
		sorter: false,
		width: 240,
		ellipsis: true
	},
	*/
	{
		title: "部门",
		key: "departments",
		sorter: false,
		width: 400,
		ellipsis: true,
		align: 'left'

	},
	{
		title: "手签",
		sorter: false,
		width: 90,
		align: "center",
		dataIndex: "manually_signed_file_path",
		fixed: "right",
	},
	{
		title: "权限",
		key: "privilege",
		sorter: false,
		width: 65,
		ellipsis: true,
		align: 'center',
		fixed: "right"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 100,
		align: "center"
	}
];

/*
const state = reactive({
	selectedRowKeys: []
});
const { selectedRowKeys } = toRefs(state);
*/

const selectedRowKeys = ref([]);

const changeSelectedRowKeys = keys => {
	selectedRowKeys.value = keys;
};

const { data, loading, run, current, pageSize, total } = usePagination(params => {
	return post("user", { ...params, ...searchState }).then(res => {
		userSource.value = res.data
		return res
	})
}, {
	defaultParams: [
		{
			page_size: 15
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});


const userSource = ref([])


const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const query = route.query;
const initData = (pag, filters, sorter) => {
	pag = Object.assign({
		current: current.value,
		pageSize: pageSize.value
	}, pag || {});
	
	filters = { ...filters, ...searchState, department_id: departmentNode.value.id };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.fullname) searchState.fullname = query.fullname;
	if (query.username) searchState.username = query.username;
	if (query.mobile) searchState.mobile = query.mobile;
	if (query.department) searchState.department = query.department;
	// router.replace({ query: {}})
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const deleteUser = (id) => {
	if (typeof id === "object") id = selectedRowKeys.value.join(",");
	if (!id) {
		proxy.$message.error("请选择需要删除的用户");
		return;
	}

	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的用户吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("user/delete", { id }).then(() => {
				proxy.$message.success("用户删除成功");

				//最后一条记录删除后需要返回上一页
				initData({ current: userSource.value.length === 1 ? Math.max(current.value - 1, 1) : current.value });
			});
		}
	});
}

const visible = ref(false);
const show = ref(false);
const formState = ref({});
const showData = ref({});
const formRef = ref();

const formRules = computed(() => {
	const { id, password } = formState.value;

	return {
		fullname: [{ required: true, message: "请输入姓名", trigger: "blur" }],
		username: [{ required: true, message: "请输入账户", trigger: "blur" }],
		mobile: [{ required: true, message: "请输入用户手机号", trigger: "blur" }],
		//department_ids: [{ required: true, message: "请选择所属部门", trigger: "blur" }],
		password: [{ required: !id ? true : false, message: "请输入密码", trigger: "blur" }],
		//position: [{ required: true, message: "请输入职务", trigger: "blur" }],
		//email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],

		/*
		username: [{ required: true, message: "请输入用户账号", trigger: "blur" }],
		password: [{ required: id ? false : true, message: "请输入登录密码", trigger: "blur" }],
		*/

		confirm_password: [{
			trigger: "blur",
			validator: (rule, value) => {
				if (!value !== !password) return Promise.reject("确认密码不一致");

				return Promise.resolve();
			}
		}],

		status: [{ required: true, message: "请选择账户状态", trigger: "blur" }],
		/*
		role_id: [{ required: true, message: "请选择角色", trigger: "blur" }],
		*/
	}
});

const addUser = () => {
	formRef.value?.clearValidate();
	visible.value = true;
	formState.value = {
		department_ids: []
	};
}
const editManuallySignedPic = (record) => {
	manuallySignedVisible.value = true;
	let file_path = [];
	if (record.manually_signed_file_path) {
		try {
			file_path = JSON.parse(record.manually_signed_file_path);
		} catch (e) {
			file_path.push({
				name: '签名照片',
				url: record.manually_signed_file_path,
			})
		}
	}
	manuallySignedFormState.value = {
		id: record.id,
		file_path
	};
}

const editUser = (record) => {
	formRef.value?.clearValidate();

	visible.value = true;
	const data = { ...record };
	data.birthday = data.birthday ? dayjs(data.birthday) : '';
	data.department_ids = record.departments && record.departments.map((d) => `${d.company_id}-${d.id}`);

	formState.value = data;
}
const showUser = (record) => {

	show.value = true;
	const data = { ...record };
	data.birthday = data.birthday ? dayjs(data.birthday) : '';
	roleOptions.forEach((role) => {
		if (data.role_id === role.value) {
			data.role_lable = role.label;
		}
	})
	data.department_lable = '';
	data.departments.forEach((department) => {
		if (department.name) {
			data.department_lable += department.name + " ";
		}
	})

	showData.value = data;
}
const handleOk = e => {
	show.value = false;
};
const saveUser = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };
			if (params.birthday) params.birthday = params.birthday.format('YYYY-MM-DD');
			params.department_ids = params.department_ids.join(',');
			params.workflow_status = 2;
			post('user/save', params).then(() => {
				proxy.$message.success('用户信息提交成功', 1);
				visible.value = false;
				initData();
			}).catch((err) => {
				proxy.$message.error(err);
			});
		})
		.catch(err => {

		});
}

const departmentSource = ref();
post("company/tree").then(data => {
	departmentSource.value = data.map((d) => {
		//判断是否为公司
		if (d.value.slice(-2) === '-0') {
			//d.disabled = true;
			//d.disableCheckbox = true;

			//分公司不可选
			d.selectable = false;
		}
		return d;
	});
});

const uploading = ref(false);

const downloadUserTpl = () => {
	window.open(`${baseURL.replace('/api', '')}/uploadfile/tpl-user.xlsx`)
}


const roleTableVisible = ref(false);
const manuallySignedVisible = ref(false);

const userId = ref();

const initUserRole = async () => {
	userRoleSource.value = await post('user/role', { user_id: userId.value });

	roleTableVisible.value = true;
}

const roleColumns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: 'center',
		fixed: "left"
	},
	{
		title: '公司名称',
		dataIndex: 'company_name',
		width: 200
	},
	{
		title: '部门名称',
		dataIndex: 'department_name',
		width: 240
	},
	{
		title: '角色名称',
		dataIndex: 'role_name',
		width: 200
	},
	{},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 140,
		align: "center"
	}
];

const userRoleSource = ref([]);
const roleDialogVisible = ref(false);

const roleFormState = ref({});
const manuallySignedFormState = ref({});
const addUserRole = () => {
	roleFormState.value = {
		user_id: userId.value
	};
	roleDialogVisible.value = true;
}
const editUserRole = (record) => {
	const data = { ...record };
	data.department_id = `${data.company_id}-${data.department_id}`;
	roleFormState.value = data;
	roleDialogVisible.value = true;
}
const roleFormRef = ref();
const manuallySigned = ref();
const saveUserRole = () => {
	roleFormRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			post('user/role/save', { ...roleFormState.value }).then(() => {
				proxy.$message.success("角色提交成功");
				roleDialogVisible.value = false;

				initUserRole();
			}).catch(err => {

			});
		})
}
const deleteRole = (id) => {
	post('user/role/delete', { id }).then(() => {
		proxy.$message.success("角色删除成功");

		initUserRole();
	})
}

const roleSource = ref([]);
post('role', { page_size: 1000, attributes: ['id', 'name'] }).then(({ data }) => {
	roleSource.value = data;
});

const roleFormRules = computed(() => {
	return {
		department_id: [{ required: true, message: "请选择部门", trigger: "blur" }],
		role_id: [{ required: true, message: "请选择角色", trigger: "blur" }],
	}
});
//上传前校验
const beforeClientUpload = file => {
	manuallySignedFormState.value.uploading = true;
	if (!['image/png', 'image/jpeg'].includes(file.type)) {
		proxy.$message.error("只能上传照片或PDF文件");
		manuallySignedFormState.value.uploading = false;
		return false;
	}
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		proxy.$message.error("只能上传10MB以下文件");
		manuallySignedFormState.value.uploading = false;
		return false;
	}
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.onload = (e) => {
			const img = new Image();
			img.onload = () => {
				const width = img.width;
				const height = img.height;
				if (parseFloat(width) > 135 || parseFloat(height) > 60) {
					manuallySignedFormState.value.uploading = false;
					proxy.$message.error("上传图片尺寸不能超过135*60px");
					reject(false);
				}
				resolve();
			};
			img.onerror = reject;
			img.src = e.target.result;
		};
		reader.readAsDataURL(file);
	});
};

// 上传并提交文件
const changeClientUpload = ({ file }) => {
	if (file.status === "done") {
		manuallySignedFormState.value.file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		manuallySignedFormState.value.uploading = false;
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		manuallySignedFormState.value.file_path = manuallySignedFormState.value.file_path.filter((item) => item.url)
	}
};

function saveUserManuallySigned() {
	manuallySigned.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			if (!manuallySignedFormState.value.file_path[0].url) {
				return proxy.$message.error('请上传附件');
			}
			const params = { ...manuallySignedFormState.value };
			params.file_path = params.file_path[0].url;
			post('user/saveManuallySignedPic', params).then(() => {
				proxy.$message.success('提交成功', 1);
				manuallySignedVisible.value = false;
				initData()
			}).catch((err) => {
				proxy.$message.error(err);
			});
		})
		.catch(err => {

		});
}
</script>

<style scoped>
:deep(.ant-tree-list) {
	/* margin-top: 20px; */
	width: 200px;
}

.toolbar {
	padding: 12px;
	background: #fff;
}

.container {
	background: #fff;
	padding: 12px;
}

.container-outer {
	display: flex;
}

.toolbar {
	margin-top: 0 !important;
}

.right {
	max-width: 83%;
	/* width: 500px; */

	box-sizing: border-box;
}

:deep(.ant-tree-list) {
	/* width: 0; */
	min-width: 245px;
}

.organization {
	/* width: 500px; */
	position: relative;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	background-color: #fff;
	border-right: 1px solid #ccc;
}
.svg-icon {
	width: 1rem;
	height: 1rem;
}
</style>
